﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.ComponentModel;


namespace inventory.Controls
{
    public class gridInventoryClearance : common.controls.baseDataGridView 
    {
        public enum ColumnNames
        {
            itemCode, subCode, techcode, itemName, unit, qty, departmentId, type, notes 
        };

        public gridInventoryClearance()
        {
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
            this.AutoArrange();
            this.myOnFind += new OnCellEvent(FindData);
            this.myOnCellValueChanged += new OnCellEvent(ValueChanged);
        }

        private void UpdateItemList(string itemCode)
        {
            if (itemCode == null)
            {
                for (int idx = 0; idx < this.Rows.Count; idx++)
                {
                    if (this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value == null) continue;
                    DataAccess.DataCache.FindITEM(this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value.ToString());
                }
            }
            else DataAccess.DataCache.FindITEM(itemCode);
        }
        public override void Init(BindingSource dataSource)
        {
            base.Init(dataSource);

            data.applicationDS.InventoryOutClearanceDataTable detailTbl = (data.applicationDS.InventoryOutClearanceDataTable)dataSource.DataSource;
            
            DataGridViewCellStyle qtyCellType = new DataGridViewCellStyle();

            string precisionStr = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskQty).ToString(); 
            qtyCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            qtyCellType.Format = "N" + precisionStr; qtyCellType.NullValue = null;

            // 
            // itemCode
            // 
            common.controls.DataGridViewTextBoxColumnExt itemCode = new common.controls.DataGridViewTextBoxColumnExt();
            itemCode.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            itemCode.HeaderText = "Mã.hàng";
            itemCode.Name = ColumnNames.itemCode.ToString();
            itemCode.Width = 90;
            itemCode.Uppercase = true;

            // 
            // subCode
            // 
            DataAccess.DataCache.LoadITEMSUBCODE();
            BindingSource itemSubCodeSource = new BindingSource();
            itemSubCodeSource.DataSource = DataAccess.DataCache.myMasterDS.itemSubCode;

            DataGridViewComboBoxColumn subCode = new DataGridViewComboBoxColumn();
            subCode.DataPropertyName = detailTbl.subCodeColumn.ColumnName;
            subCode.HeaderText = " +";
            subCode.Name = ColumnNames.subCode.ToString();
            subCode.Width = 50;
            subCode.DataSource = itemSubCodeSource;
            subCode.DisplayMember = DataAccess.DataCache.myMasterDS.itemSubCode.codeColumn.ColumnName;
            subCode.ValueMember = DataAccess.DataCache.myMasterDS.itemSubCode.codeColumn.ColumnName;
            subCode.DefaultCellStyle.NullValue = " "; //Must be one space at least

            // 
            // techCode
            // 
            BindingSource itemSource = new BindingSource();
            itemSource.DataSource = DataAccess.DataCache.myMasterDS.Item;
            DataGridViewComboBoxColumn techCode = new DataGridViewComboBoxColumn();
            techCode.DataSource = itemSource;
            techCode.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            techCode.DisplayMember = DataAccess.DataCache.myMasterDS.Item.techCodeColumn.ColumnName;
            techCode.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            techCode.HeaderText = "Mã.kỹ.thuật";
            techCode.Name = ColumnNames.techcode.ToString();
            techCode.ReadOnly = true;
            techCode.Width = 100;
            techCode.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            techCode.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG; 
            techCode.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            techCode.Visible = false; 

            // 
            // itemName
            // 
            DataGridViewComboBoxColumn itemName = new DataGridViewComboBoxColumn();
            itemName.DataSource = itemSource;
            itemName.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            itemName.DisplayMember = DataAccess.DataCache.myMasterDS.Item.nameColumn.ColumnName;
            itemName.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            itemName.HeaderText = "Diễn giải";
            itemName.Name = ColumnNames.itemName.ToString();
            itemName.ReadOnly = true;
            
            itemName.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            itemName.Width = 170;
            itemName.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            itemName.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG; 
            
            // 
            // unit
            // 
            DataGridViewComboBoxColumn unit = new DataGridViewComboBoxColumn();
            unit.DataSource = itemSource;
            unit.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            unit.DisplayMember = DataAccess.DataCache.myMasterDS.Item.unitColumn.ColumnName;
            unit.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            unit.HeaderText = "ĐVT";
            unit.Name = ColumnNames.unit.ToString();
            unit.ReadOnly = true;
            unit.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            unit.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            unit.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG; 
            unit.Width = 60;
            // 
            // Qty
            // 
            DataGridViewTextBoxColumn qty = new DataGridViewTextBoxColumn();
            qty.DataPropertyName = detailTbl.qtyColumn.ColumnName;
            qty.HeaderText = "Lượng";
            qty.Name = ColumnNames.qty.ToString();
            qty.DefaultCellStyle = qtyCellType;
            qty.Width = 80;


            // 
            // type
            // 
            BindingSource usedTypeSource = new BindingSource();
            DataAccess.DataCache.LoadInvAdvClearingTypes();
            usedTypeSource.DataSource = DataAccess.DataCache.myMasterDS.inventoryOutClearanceTypes;
            DataGridViewComboBoxColumn useType = new DataGridViewComboBoxColumn();
            useType.DataSource = usedTypeSource;
            useType.DataPropertyName = detailTbl.typeColumn.ColumnName;
            useType.DisplayMember = DataAccess.DataCache.myMasterDS.inventoryOutClearanceTypes.description1Column.ColumnName;
            useType.ValueMember = DataAccess.DataCache.myMasterDS.inventoryOutClearanceTypes.codeColumn.ColumnName;
            useType.HeaderText = "Sử dụng";
            useType.Name = ColumnNames.type.ToString();
            useType.Width = 120;

            // 
            // department
            // 
            BindingSource departmentSource = new BindingSource();
            DataAccess.DataCache.LoadDEPARTMENT();
            departmentSource.DataSource = DataAccess.DataCache.myMasterDS.department;

            DataGridViewComboBoxColumn department = new DataGridViewComboBoxColumn();
            department.DataSource = departmentSource;
            department.DataPropertyName = detailTbl.deptIdColumn.ColumnName;
            department.DisplayMember = DataAccess.DataCache.myMasterDS.department.nameColumn.ColumnName;
            department.ValueMember = DataAccess.DataCache.myMasterDS.department.departmentIdColumn.ColumnName;
            department.HeaderText = "Nơi.sử.dụng";
            department.Name = ColumnNames.departmentId.ToString();
            department.Width = 120;
            // 
            // Notes
            // 
            DataGridViewTextBoxColumn notes = new DataGridViewTextBoxColumn();
            notes.DataPropertyName = detailTbl.notesColumn.ColumnName;
            notes.HeaderText = "Ghi chú";
            notes.Name = ColumnNames.notes.ToString();
            notes.Width = 200;

            // 
            // myDetailGrid
            // 
            this.Visible = true;
            this.DataSource = dataSource;

            this.ReadOnly = false;
            this.ScrollBars = ScrollBars.Vertical;
            this.AutoGenerateColumns = false;
            this.Columns.Clear();
            this.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
                    itemCode,subCode,techCode,itemName,unit,qty,useType, department,notes});
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
            this.DisbaleReadOnlyColumns();

        }
        protected override void OnDefaultValuesNeeded(DataGridViewRowEventArgs e)
        {
            try
            {
                int saveDeptId = -1;
                string saveType = null;
                if (this.CurrentRow != null)
                {
                    int.TryParse(this.CurrentRow.Cells[ColumnNames.departmentId.ToString()].Value.ToString(), out saveDeptId);
                    if (this.CurrentRow.Cells[ColumnNames.type.ToString()].Value != null)
                        saveType = this.CurrentRow.Cells[ColumnNames.type.ToString()].Value.ToString();
                }
                base.OnDefaultValuesNeeded(e);
                if (e == null) return;
                if (myDataSource.Current != null)
                {
                    data.applicationDS.InventoryOutClearanceRow dataRow;
                    dataRow = (data.applicationDS.InventoryOutClearanceRow)((DataRowView)myDataSource.Current).Row;
                    DataAccess.DataLibs.InitData(dataRow);
                    if (saveDeptId >= 0) dataRow.deptId = saveDeptId;
                    if (saveType !=null) dataRow.type = saveType;
                }
            }
            catch (Exception er)
            {
                ErrorHandler(this, er);
            }
        }

        public override void Refresh()
        {
            if (IsOnProcessing) return;
            try
            {
                IsOnProcessing = true;
                UpdateItemList(null);
                IsOnProcessing = false;
                base.Refresh();
            }
            catch (Exception er)
            {
                IsOnProcessing = false;
                ErrorHandler(this, er);
            }
        }

        private void ValueChanged(object sender, common.controls.GridEventArgs e)
        {
            if (this.CurrentCell == null || !this.IsValidCell(e.RowIndex, e.ColumnIndex)) return;
            if (this.Columns[e.ColumnIndex].Name == ColumnNames.itemCode.ToString())
            {
                string itemCode = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (common.StringLibs.IsNullOrEmpty(itemCode) == false)
                {
                    bool HaveMarker = common.SysLibs.HaveFindMarker(ref itemCode);
                    if (HaveMarker == false)
                    {
                        string code = application.AppLibs.GetItemCodeFromCodeId(itemCode);
                        if (code != null)
                        {
                            itemCode = code;
                            this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = itemCode;
                        }
                    }
                    data.masterDS.ItemRow itemRow = DataAccess.DataCache.FindITEM(itemCode);
                    if (itemRow == null) FindData(this, new common.controls.GridEventArgs(e.RowIndex, e.ColumnIndex));
                }
            }
        }
        private void FindData(object sender, common.controls.GridEventArgs arg)
        {
            string findCode = this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].EditedFormattedValue.ToString(); ;
            if (this.CurrentCell == null) return;
            //Code
            if (this.Columns[arg.ColumnIndex].Name.Trim() == ColumnNames.itemCode.ToString())
            {
                application.dataFind.myItemFind.Find(findCode, true);
                data.masterDS.ItemRow itemRow = application.dataFind.myItemFind.selectedDataRow;
                if (itemRow != null)
                {
                    this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].Value = itemRow.itemCode;
                    UpdateItemList(itemRow.itemCode);
                }
                else this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].Value = DBNull.Value;
                this.myDataSource.ResetCurrentItem();
                this.myDataSource.EndEdit(); 
            }
        }
    }
}
